package com.wuyou.simple;

import java.sql.Array;
import java.util.*;

/**
 * 1636. 按照频率将数组升序排序
 */
public class FrequencySort {

    public static void main(String[] args) {
        FrequencySort frequencySort = new FrequencySort();
        int[] nums = {2, 3, 1, 3, 2};
        frequencySort.solution_2(nums);
    }


    public int[] solution_2(int[] nums) {
        int[] res = new int[nums.length];
        Map<Integer, Integer> map = new HashMap<>();

        List<Integer> numList = new ArrayList<>();

        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
            numList.add(nums[i]);
        }

        numList.sort((a, b) -> {
            System.out.println(a + "," + b);
            int aCount = map.get(a);
            int bCount = map.get(b);
            if(aCount == bCount) return b - a;

            return aCount - bCount;
        });
        return numList.stream().mapToInt(Integer::intValue).toArray();
    }

    public int[] solution_1(int[] nums) {
        int[] res = new int[nums.length];
        Arrays.sort(nums);
        Map<Integer, Integer> map = new HashMap<>();
        Map<Integer, List<Integer>> listMap = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            Integer temp = nums[i];
            int count = map.getOrDefault(temp, 0) + 1;
            map.put(temp, count);
            List<Integer> list = listMap.getOrDefault(count - 1, new ArrayList<>());
            List<Integer> list1 = listMap.getOrDefault(count, new ArrayList<>());
            if (list.contains(temp)) {
                for (int j = 0; j < count; j++) {
                    list1.add(temp);
                }
                list.removeIf(item -> temp == item);
                listMap.put(count - 1, list);
                listMap.put(count, list1);
            } else {
                list1.add(temp);
                listMap.put(count, list1);
            }
        }

        Set<Integer> integers = listMap.keySet();
        int index = 0;
        for (Integer i : integers) {

            List<Integer> list = listMap.get(i);
            for (int j = list.size() - 1; j >= 0; j--) {
                res[index] = list.get(j);
                index++;
            }

        }
        return res;
    }
}
